package com.bieyang.anjia.ui.activity;

import org.json.JSONException;
import org.json.JSONObject;
import org.webrtc.mqttclientsample.LogUtis;
import org.webrtc.mqttclientsample.Message;
import org.webrtc.mqttclientsample.MessageService;

import cn.jpush.android.api.JPushInterface;

import com.bieyang.anjia.R;
import com.bieyang.anjia.utils.Constants;
import com.bieyang.anjia.utils.SharedPrefsUtil;
import com.bieyang.anjia.utils.SubUtils;
import com.bieyang.anjia.utils.Util;
 
import com.umeng.analytics.MobclickAgent;

import de.greenrobot.event.EventBus;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.ProgressBar;

/**
 * app启动页面，如果是第一次安装进入欢迎界面，如果登陆过主机主界面则进入主机主界面，其他则进入登陆提示界面
 * 
 * @author wjh
 * 
 */
@SuppressLint("HandlerLeak")
public class AcLogo extends BaseActivity {
	public static final int SEND_INTENT_ACGUID = 1001;

	// version upgrade
	String newVersion;
	boolean isFinish = false;
	private int index = 0;
	private ProgressBar progressBar;
	public Dialog dialog, progressDialog;
	// public TNewVerInfo verinfo;
	String lVersion;

	MyServiceConnection conn;
	Context con;

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case Constants.GET_VERSION_OK:
				// verinfo = new TNewVerInfo();
				String data = msg.obj.toString();
				Log.d("data", data);

				JSONObject dataJson;
				try {
					dataJson = new JSONObject(data);

					JSONObject jobj = dataJson.getJSONObject("data");
					App.verinfo.sNewVerNo = jobj.get("version").toString();
					int typeUpgrade = jobj.getInt("typeCode");
					App.verinfo.iFileSize = jobj.getInt("size");
					App.verinfo.sUpDownLinkAddr = jobj.get("url").toString();
					App.verinfo.sUpMsg = jobj.get("content").toString();

					App.verinfo.sFileName = "anjia.apk";
					lVersion = Util.getVersionName(App.mContext);

					// Log.d("lVersion", ""+lVersion+"-r-:"+rVersion);

					if (Util.compareVersion(lVersion, App.verinfo.sNewVerNo)) { // 有版本更新
						switch (typeUpgrade) {
						case 1: // 创可贴更新,主机主界面菜单按钮红点提示
							SharedPrefsUtil.putValue(App.mContext,
									"newVersion", 1);
							break;
						case 2:// 弹窗升级
							SharedPrefsUtil.putValue(App.mContext,
									"newVersion", 2);
							// popUpVersion(2);
							break;
						case 3:// 强制更新
							SharedPrefsUtil.putValue(App.mContext,
									"newVersion", 3);
							// popUpVersion(3);
							break;

						default:
							break;
						}

					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				break;

			case Constants.LOGIN_SUCESS:
				/*
				 * register call
				 */
				conn = new MyServiceConnection();
				Intent serviceIntent = new Intent(con,
						MessageService.class);
				bindService(serviceIntent, conn, BIND_AUTO_CREATE);

				registerEvent();
				MessageService.startService(con, SubUtils.getUuid(con));
				
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub 
						startActivity(new Intent(AcLogo.this, AcMain.class));
						finish();
					}
				}, 1000);
				break;

			case SEND_INTENT_ACGUID:
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						startActivity(new Intent(AcLogo.this, AcGuid.class));
						finish();
					}
				}, 1000);
				break;

			default:
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						startActivity(new Intent(AcLogo.this, AcTiYan.class));
						finish();
					}
				}, 2000);

				break;
			}

		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_logo);
		App.mContext = AcLogo.this;
		con=AcLogo.this;

		// testin**********
//		TestinAgent.init(this);

		// *****************

		JPushInterface.init(getApplicationContext()); // 极光初始化

		// FIXME 友盟统计初始化 注：以下操作必须在第一个启动界面中添加......................
		MobclickAgent.setDebugMode(true);
		MobclickAgent.openActivityDurationTrack(false);
		MobclickAgent.updateOnlineConfig(this);
		// .....................................................................

		// 检测版本更新,只做记录，不做界面处理，界面处理在下一个界面做
		App.netManager.getVersionInfo(handler);

		// Log.d("firstLogined",
		// ""
		// + SharedPrefsUtil.getBooleanValue(App.mContext,
		// "firstLogined", false));
		if (!SharedPrefsUtil.getBooleanValue(App.mContext, "firstLogined",
				false)) {
			// 第一次进入
			SharedPrefsUtil.putValue(App.mContext, "firstLogined", true);
			handler.sendEmptyMessage(SEND_INTENT_ACGUID);
		} else {
			// 如果登陆过主机，则执行登陆操作
			if (SharedPrefsUtil.getBooleanValue(App.mContext, "loginMain",
					false)) {
				App.netManager.loginEx(handler);
			} else {
				handler.sendEmptyMessage(-1);

			}

		}
		// BasicHandler.init(this.getApplication());

	}
	
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (null != conn)
			unbindService(conn);
		EventBus.getDefault().unregister(this);
	}

	private class MyServiceConnection implements
			android.content.ServiceConnection {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
		}

	}

	private void registerEvent() {
		EventBus.getDefault().register(this, "onMessage", Message.class);
	}

	public void onMessage(final Message message) {
		LogUtis.log("from:" + message.getFrom() + "," + "to:" + message.getTo()
				+ "," + "content:" + message.getContent() + "," + "type:"
				+ message.getType());
		switch (message.getType()) {
		// case CHAT:
		// mReceiveMessage.post(new Runnable() {
		//
		// @Override
		// public void run() {
		// mReceiveMessage.setText(mReceiveMessage.getText() + "\n"
		// + "来自" + message.getFrom() + "说:"
		// + message.getContent());
		// }
		// });
		// break;

		case PHONE:

			break;

		default:
			break;
		}
	}

}
